/**
 * 封装localStorage
 * 增加对JSON对象的转换
 */
const localDb = {
  /**
   * 按key存贮数据value到localStorage
   * @param {string} key   存贮数据的唯一标识
   * @param {T} value 所要存贮的数据
   */
  set<T = string>(key: string, value: T) {
    if (!value) {
      window.localStorage.removeItem(key);
    } else {
      const val = Array.isArray(value) || typeof value === 'object' ? JSON.stringify(value) : value;
      window.localStorage.setItem(key, val as string);
    }
  },
  /**
   * 通过key从localStorage获取数据
   * @param  {string} key  获取数据的可以标识
   * @return {T}  返回空，字符串或者对象
   */
  get<T>(key: string): T | undefined {
    const str = window.localStorage.getItem(key) || '';
    if (this.isJSONStr(str)) {
      try {
        return JSON.parse(str) as T;
      } catch (err) {
        return undefined;
      }
    }
    if (str === null) {
      return undefined;
    }
    return str as unknown as T;
  },

  /**
   * 按key存贮数据value到sessionStorage
   * @param {String} key   存贮数据的唯一标识
   * @param {T} value 所要存贮的数据
   */
  setSession<T>(key: string, value: T) {
    if (!value) {
      window.sessionStorage.removeItem(key);
    } else {
      const val = Array.isArray(value) || typeof value === 'object' ? JSON.stringify(value) : value;
      window.sessionStorage.setItem(key, val as string);
    }
  },

  /**
   * 通过key从sessionStorage获取数据
   * @param  {String} key  获取数据的可以标识
   * @return {String, Object}  返回空，字符串或者对象
   */
  getSession<T>(key: string): T | undefined {
    const str = window.sessionStorage.getItem(key) || '';
    if (this.isJSONStr(str)) {
      try {
        return JSON.parse(str) as T;
      } catch (err) {
        return undefined;
      }
    }
    return str as unknown as T;
  },

  /**
   * 判断是否是JSON string
   * @param  {String}  str 所要验证的字符串
   * @return {Boolean}   是否是JSON字符串
   */
  isJSONStr(str: string) {
    return (str.charAt(0) === '{' && str.charAt(str.length - 1) === '}') || (str.charAt(0) === '[' && str.charAt(str.length - 1) === ']');
  },
  /**
   * 清空localStorage
   * @return 无返回NULL
   */
  clear(key: string | undefined) {
    if (key) {
      window.localStorage.removeItem(key);
    } else {
      window.localStorage.clear();
    }
  },

  /**
   * sessionStorage
   * @return 无返回NULL
   */
  clearSession(key: string | undefined) {
    if (key) {
      window.sessionStorage.removeItem('key');
    } else {
      window.sessionStorage.clear();
    }
  },

  // jwtToken
  setjwtToken(jwtTokenKey: string, data: any, persistent = false) {
    if (persistent) {
      this.set(jwtTokenKey, data);
    } else {
      localStorage.setItem(jwtTokenKey, JSON.stringify(data));
    }
  },
};

export default localDb;
